package leetcode.problems;

/**
 * _0414 Best Time to Buy and Sell Stock
 * 卖股票的最好时机
 * Created by gmwang on 2018/3/23
 */
public class _0414BestTimetoBuyandSellStock {
    /**
     *  Say you have an array for which the ith element is the price of a given stock on day i.
         If you were only permitted to complete at most one transaction
        (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

     Example 1:
         Input: [7, 1, 5, 3, 6, 4]
         Output: 5
        max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
     Example 2:
         Input: [7, 6, 4, 3, 1]
         Output: 0
         In this case, no transaction is done, i.e. max profit = 0.

         假设你有一个数组，其中i元素是给定股票在第一天的价格。
         如果你只允许最多完成一个交易（即买入一个股票，卖出一份股票），设计一个最大利润的算法。
            ！！！要求时间复杂度是 o（1）。
     */
    /**
     * 思路：
     * 1. 比较最大值，记录
     * 2. 比较最小值，记录
     * 3. 最大值 = max(最大值，当前-最小值)
     *
     *
     * @param
     * @return
     */
    public static int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2) return 0;
        int maxProfit = 0, minPrice = prices[0];
        for(int i = 1; i < prices.length; i++) {
            if(prices[i] > prices[i - 1]) {
                maxProfit = Math.max(maxProfit,prices[i]-minPrice);
            }else{
                minPrice = Math.min(prices[i],minPrice);
            }
        }
        return maxProfit;
    }
    public static void main(String[] args) {
        int [] nums = {7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(nums));
    }
}

